#ifndef _TWIT_SERVER_H
#define _TWIT_SERVER_H

#include <iostream>
#include "tcpwrapper.h"
#include <map>
#include "ClientServ.h"
#include <stdio.h>
#include <stdlib.h>
#include <sstream>
#include <fstream>
using namespace std;

class Server{
private:
	class mapCmp {
	public:
		bool operator()( const string& first, const string& second) const {
			size_t firstLength = first.length();
			size_t secondLength = second.length();
			
			for ( size_t i = 0; (i < firstLength) && (i < secondLength); i++ ) {
				if ( tolower(first[i]) == tolower(second[i]) ) {
					if ( first[i] != second[i] )
						return first[i] < second[i];
				}
				else
					return ( tolower(first[i]) < tolower(second[i]) );
			}

			return ( firstLength < secondLength );
		}
	};
	
	
	fstream log;
	int _port;
	int _listenPort;
	int _current_max_fd;
	fd_set _listenSet;
	typedef map<string,Client*, mapCmp> ClientsList;
	ClientsList _clients;
	typedef map<int,Client*> ClientsByFd; //maps are automatically order according to Less<T>
	ClientsByFd _clientsByFd;
	void mainError(const char* msg, bool toDo);
	void insertNewClient();
	void sendServerMessage(string msg);
	bool SendServerMessage(string msg,Client* cl);
	void shutdown();
	void removeClientByFd(int fd);
	bool InterpretCommand(int current_fd,string &msg);

	bool DirectMessage(int current_fd,string &msg);
	void SendErrorToUknown(int fd, string msg,bool toClose);
	 string createMessagePrefix(string fromClient);
	bool Who(int current_fd,string &msg);
	bool Disconnect(int current_fd,string &msg);

	bool sendMessage(int fd, string message);
	void ServermainError(string msg, bool toDo);


	bool Follow(int current_fd,string &name);
	bool Unfollow(int current_fd,string &name);
	bool Twit(int current_fd,string &msg);
	

public:
	Server(int port)
	{
		_port=port;
		FD_ZERO(&_listenSet);
	}
	~Server(){
		close(_port);
	}
	void startServer();
};

#endif
